package com.netflix.basic.controller;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.eureka.CloudEurekaClient;
import org.springframework.cloud.util.ProxyUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/apps")
@RestController
public class RefreshAppsController {

	@Autowired
	EurekaClient eurekaClient;

	@Value("${eureka.client.serviceUrl.defaultZone}")
	String defaultZone;

	@RequestMapping(value = "/refresh", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public void refreshLocalApps() {

		System.out.println("************** refreshLocalApps() **************");
//		CloudEurekaClient cloudEurekaClient = ProxyUtils.getTargetObject(eurekaClient);
//		cloudEurekaClient.fetchRegistry(false);
	}

	@RequestMapping(value = "/remote", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public List<String> remoteApps() {

		List<String> instanceIds = new ArrayList<>();
		Applications applications = eurekaClient.getApplications(defaultZone);
		List<Application> apps = applications.getRegisteredApplications();
		for (Application app : apps) {
			for (InstanceInfo instance : app.getInstances()) {
				instanceIds.add(instance.getInstanceId());
			}
		}
		return instanceIds;
	}

	@RequestMapping(value = "/local", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public List<String> localApps() {

		List<String> instanceIds = new ArrayList<>();
		Applications localApplications = eurekaClient.getApplications();
		List<Application> localApps = localApplications.getRegisteredApplications();
		for (Application app : localApps) {
			for (InstanceInfo instance : app.getInstances()) {
				instanceIds.add(instance.getInstanceId());
			}
		}
		return instanceIds;
	}

	@RequestMapping(value = "/offline", method = RequestMethod.DELETE)
	public void offLine() {
		eurekaClient.shutdown();
	}
}
